package org.springblade.core.ds.strategy;


import org.springblade.core.ds.SQResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InsertBuilder {
    private String table;
    private List<Map<String, Object>> lineData;
    private Map<String, Object> line;

    /**
     * 构造
     *
     * @param inTable
     */
    public InsertBuilder(String inTable) {
        this.table = inTable;
        this.lineData = new ArrayList<>();
        //默认新增行
        newLine();
    }

    /**
     * 下一行
     */
    public void newLine() {
        if (line == null || line.size() > 0) {
            this.line = new HashMap<>();
            lineData.add(line);
        }
    }

    /**
     * 赋值
     *
     * @param columnName
     * @param value
     * @return
     */
    public InsertBuilder set(String columnName, Object value) {
        if (value != null) {
            line.put(columnName, value);
        }
        return this;
    }


    /**
     * 构建
     *
     * @return
     */
    public SQResult build() {
        //取得所有列
        List<String> columnList = new ArrayList<>();
        for (Map<String, Object> lineData : lineData) {
            for (String key : lineData.keySet()) {
                if (columnList.contains(key)) {
                    continue;
                }
                columnList.add(key);
            }
        }
        if (columnList == null || columnList.size() == 0) {
            return new SQResult().setSql(null).setValueList(null);
        }
        //构造插入SQL
        StringBuilder sql = new StringBuilder();
        StringBuilder p = new StringBuilder();
        sql.append(" insert into ").append(table).append("(");
        for (int i = 0; i < columnList.size(); i++) {
            if (i > 0) {
                sql.append(",");
                p.append(",");
            }
            sql.append(columnList.get(i));
            p.append("?");
        }
        sql.append(") values (").append(p).append(")");

        //更新
        List<List<Object>> valueList = new ArrayList<>();
        for (Map<String, Object> valueMap : lineData) {
            if (valueMap == null || valueMap.size() == 0) {
                continue;
            }
            List<Object> outputValueList = new ArrayList<>();
            for (String column : columnList) {
                outputValueList.add(valueMap.get(column));
            }
            valueList.add(outputValueList);
        }
        return new SQResult().setSql(sql.toString()).setValueList(valueList);
    }

}
